package org.jeecg.modules.user.abnormal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UuidUtils;
import org.jeecg.common.api.MemberAPI;
import org.jeecg.common.api.dto.MemberDTO;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.bicycle.order.entity.BikeVehicleOrder;
import org.jeecg.modules.bicycle.order.mapper.BikeVehicleOrderMapper;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.param.fault.vo.FaultFileRes;
import org.jeecg.modules.param.station.entity.BikeStation;
import org.jeecg.modules.param.station.mapper.BikeStationMapper;
import org.jeecg.modules.system.announcement.service.IBikeAnnouncementService;
import org.jeecg.modules.user.abnormal.dto.FaultReq;
import org.jeecg.modules.param.fault.vo.FaultRes;
import org.jeecg.modules.user.abnormal.service.FaultService;
import org.jeecg.modules.bicycle.vehicle.entity.BikeVehicle;
import org.jeecg.modules.bicycle.vehicle.mapper.BikeVehicleMapper;
import org.jeecg.modules.param.fault.entity.BikeFaultSubmit;
import org.jeecg.modules.param.fault.entity.BikeFaultSubmitFile;
import org.jeecg.modules.param.fault.mapper.BikeFaultSubmitFileMapper;
import org.jeecg.modules.param.fault.mapper.BikeFaultSubmitMapper;
import org.jeecg.modules.param.pile.entity.BikePile;
import org.jeecg.modules.param.pile.mapper.BikePileMapper;
import org.jeecg.modules.utils.BikeResult;
import org.jeecg.modules.utils.RandomCodeUtils;
import org.jeecg.modules.utils.YueYueNiaoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.beans.Transient;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class FaultServiceImpl implements FaultService {
    @Autowired
    private MemberAPI memberAPI;
    @Autowired
    private BikeFaultSubmitMapper bikeFaultSubmitMapper;
    @Autowired
    private BikeVehicleMapper bikeVehicleMapper;
    @Autowired
    private BikePileMapper bikePileMapper;
    @Resource
    private BikeVehicleOrderMapper bikeVehicleOrderMapper;
    @Autowired
    private BikeStationMapper bikeStationMapper;
    @Autowired
    private BikeFaultSubmitFileMapper bikeFaultSubmitFileMapper;
    @Autowired
    private IBikeAnnouncementService bikeAnnouncementService;
    @Value("${application.domain}")
    public String domain;

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    @Transient
    @Override
    public BikeResult insertFault(FaultReq faultReq, HttpServletRequest request) {

        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(accessToken);
        MemberDTO member = memberAPI.getMember(username);
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmssSSS");

        if (StringUtils.isEmpty(faultReq.getPileCode())) {
            return BikeResult.error("0", "请填写车桩号", null);
        }
        if (faultReq.getPileCode().length() != 11) {
            return BikeResult.error("0", "车桩编号有误", null);
        }
        //网点
        String stationCode = faultReq.getPileCode().substring(0, 5);
        //车桩
        String pileCode = faultReq.getPileCode().substring(5, 7);
        String checkCode = faultReq.getPileCode().substring(7, 11);
        //获取网点信息
        BikeStation bikeStation = bikeStationMapper.selectOne(new QueryWrapper<BikeStation>().eq("code", stationCode));
        if (bikeStation==null){
            return BikeResult.error("0", "车桩编号有误", null);
        }
        //获取车桩信息
        BikePile bikePileData = bikePileMapper.selectOne(new QueryWrapper<BikePile>().eq("station_id",bikeStation.getId()).eq("code",pileCode));
        if (bikePileData==null){
            return BikeResult.error("0", "车桩编号有误", null);
        }
        if (!bikePileData.getCheckCode().equals(checkCode)){
            return BikeResult.error("0", "车桩编号有误", null);
        }
        BikeFaultSubmit bikeFaultSubmit = new BikeFaultSubmit();

        //骑行记录获取车辆信息
        BikeVehicleOrder bikeVehicleOrder = bikeVehicleOrderMapper.selectOne(new QueryWrapper<BikeVehicleOrder>().eq("pick_user", member.getId()).isNull("park_time"));
        //车辆信息
        if (bikeVehicleOrder==null){
            QueryWrapper<BikeVehicle> wrapper = new QueryWrapper<>();
            if (StringUtils.isEmpty(faultReq.getVehicleCode())){
                wrapper.eq("pile_id", bikePileData.getId());
            }else {
                wrapper.eq("code", faultReq.getVehicleCode());
            }
            BikeVehicle vehicle = bikeVehicleMapper.selectOne(wrapper);
            if (vehicle!=null){
                bikeFaultSubmit.setVehicleId(vehicle.getId());
            }
        }else {
            bikeFaultSubmit.setVehicleId(bikeVehicleOrder.getVehicleId());
        }


        //新增上报故障记录
        bikeFaultSubmit.setStationId(bikeStation.getId());
        bikeFaultSubmit.setPileId(bikePileData.getId());

        String uuid = YueYueNiaoUtils.getUUid();
        bikeFaultSubmit.setId(uuid);
        bikeFaultSubmit.setCode("GZ"+sdf.format(new Date()));
        bikeFaultSubmit.setUserId(member.getId());
        bikeFaultSubmit.setUserType("1");
        bikeFaultSubmit.setFaultType(faultReq.getFaultType()+"");
        bikeFaultSubmit.setContent(faultReq.getContent());
        bikeFaultSubmit.setIsDispatch(BikeConstant.y_n_no);
        int param = bikeFaultSubmitMapper.insert(bikeFaultSubmit);
       //保存图片地址
        if (faultReq.getBikeFaultFiles().size()>=1){
            List<BikeFaultSubmitFile>  fileList= faultReq.getBikeFaultFiles();
            for (BikeFaultSubmitFile fs:fileList) {
                BikeFaultSubmitFile bikeFaultSubmitFile = new BikeFaultSubmitFile();
                bikeFaultSubmitFile.setFaultId(uuid);
                bikeFaultSubmitFile.setFileUrl(fs.getFileUrl());
                bikeFaultSubmitFileMapper.insert(bikeFaultSubmitFile);
            }
        }
        if (param==1){
            //List<String> sysUserIds = bikeAnnouncementService.getSysUserIds(BikeConstant.sys_msg_report);
            //bikeAnnouncementService.addSysMsgByUser(sysUserIds,BikeConstant.sys_msg_report_text,member.getCode(),BikeConstant.sys_msg_report,uuid);
            return BikeResult.ok("1","上传故障成功！",param);
        }
        return BikeResult.error("0","上传故障失败",null);
    }

    @Override
    public BikeResult getFaultList(Integer pageNum, Integer pageSize, HttpServletRequest request) {
        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String phone = JwtUtil.getUsername(accessToken);
        Page<FaultRes> page = new Page<>(pageNum,pageSize);
        IPage<FaultRes> result= bikeFaultSubmitMapper.getBikeFaultList(page,phone);
        for (FaultRes submit:result.getRecords()) {
            submit.setPileCode(submit.getStationCode() + submit.getPileCode() + submit.getCheckCode());

            QueryWrapper qw = new QueryWrapper();
            qw.eq("fault_id", submit.getId());
            List<BikeFaultSubmitFile> fileList = bikeFaultSubmitFileMapper.selectList(qw);

         if (fileList.size()!=0){
             for (int i=0;i<fileList.size();i++){
                 fileList.get(i).setFileUrl(domain+ fileList.get(i).getFileUrl());
             }
         }
            submit.setBikeFaultFiles(fileList);
        }
       return BikeResult.ok("1","查询成功！",result);
    }
}
